//
//  LSHomeArticleDetailVController.m
//  LookScore
//
//  Created by wr on 2018/1/23.
//  Copyright © 2018年 ChongQingXunTiCompany. All rights reserved.
//

#import "LSHomeArticleDetailVController.h"
#import "LSHttpEnclosureTool.h"
#import "LSAccountArchive.h"
#import <WebKit/WKWebView.h>
#import <WebKit/WebKit.h>
#import "DXShareView.h"
#import <TencentOpenAPI/TencentOAuth.h>
#import <TencentOpenAPI/QQApiInterfaceObject.h>
#import <TencentOpenAPI/QQApiInterface.h>
#import "AppDelegate.h"
#import "WXApi.h"
#import "WechatAuthSDK.h"
#import "WXApiObject.h"
#import "MBProgressHUD+MJ.h"
@interface LSHomeArticleDetailVController ()<WKUIDelegate,WKNavigationDelegate,UIScrollViewDelegate,TencentSessionDelegate,TencentWebViewDelegate,ADelegate>
@property(nonatomic,strong)UIScrollView *scrollView;
@property(nonatomic,strong)UILabel *titleLable;
@property(nonatomic,strong)UILabel *infoSourceLable;
@property(nonatomic,strong)UIImageView *readIcon;
@property(nonatomic,strong)UILabel *readCoutLable;
@property(nonatomic,strong)WKWebView *webView;
@end

@implementation LSHomeArticleDetailVController{
    TencentOAuth * tencentOAuth;
    AppDelegate * appdelegate;
    NSString *_urlStr;
//    LSHomeArticleQueryList *_articleList;
    NSString *_titleStr;
    NSString *_describStr;
    NSString *_imageUrl;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.view.backgroundColor = [UIColor whiteColor];
    
    [self getData];
}
- (void)initUI{
    
    self.title = @"详情";
    
    UIButton*rightButton = [[UIButton alloc]initWithFrame:CGRectMake(0,0,30,40)];
    [rightButton setImage:[UIImage imageNamed:@"share_issue_white"]forState:UIControlStateNormal];
    [rightButton addTarget:self action:@selector(action_ShareBtn:) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem*rightItem = [[UIBarButtonItem alloc]initWithCustomView:rightButton];
    self.navigationItem.rightBarButtonItem= rightItem;
    
    
//
//
//
//
//    UIScrollView *scrollView = [[UIScrollView alloc] init];
//    scrollView.backgroundColor = LSTitleWhiteColor;
//    scrollView.alwaysBounceVertical = YES;
//    scrollView.scrollEnabled = YES;
//    scrollView.userInteractionEnabled = YES;
//    scrollView.delegate = self;
////    scrollView.contentSize = CGSizeMake(LSScreenWidth, 5000);
//    self.scrollView = scrollView;
//    [self.view addSubview:self.scrollView];
//    self.scrollView.sd_layout.rightEqualToView(self.view).topEqualToView(self.view).leftEqualToView(self.view).bottomEqualToView(self.view);
//
//    UILabel *titleLab=[[UILabel alloc]init];
//    titleLab.font=[UIFont systemFontOfSize:23];
//    titleLab.textColor=LSTitleGrayColor1;
//    [titleLab sizeToFit];
//    titleLab.numberOfLines=2;
//    self.titleLable = titleLab;
//    [self.scrollView addSubview:self.titleLable];
//    self.titleLable.sd_layout.leftEqualToView(self.scrollView).offset(14).topEqualToView(self.scrollView).offset(13).rightEqualToView(self.scrollView).offset(-14).heightIs(60);
//
//    UILabel *infoSourceLab=[[UILabel alloc]init];
//    infoSourceLab.font=LSFontSize13;
//    infoSourceLab.textColor=LSTitleGrayColor3;
//    self.infoSourceLable = infoSourceLab;
//    [self.scrollView addSubview:self.infoSourceLable];
//    self.infoSourceLable.sd_layout.leftEqualToView(self.titleLable).topSpaceToView(self.titleLable, 10).widthIs(200).heightIs(20);
//
//    UILabel *readCoutLab = [[UILabel alloc] init];
//    readCoutLab.font=LSFontSize13;
//    readCoutLab.textColor=LSTitleGrayColor3;
//    self.readCoutLable = readCoutLab;
//    [self.scrollView addSubview:self.readCoutLable];
//    self.readCoutLable.sd_layout.rightEqualToView(self.scrollView).offset(-14).topSpaceToView(self.titleLable, 10).widthIs(50).heightIs(20);
//
//    UIImageView *readIcon = [[UIImageView alloc] init];
//    self.readIcon = readIcon;
//    [self.scrollView addSubview:self.readIcon];
//    self.readIcon.sd_layout.leftEqualToView(self.readCoutLable).offset(-30).topSpaceToView(self.titleLable, 10).widthIs(20).heightIs(20);
    
    
    WKWebView *webView = [[WKWebView alloc] init];
    webView.backgroundColor = [UIColor redColor];
    webView.UIDelegate = self;
    webView.navigationDelegate = self;
//    webView.userInteractionEnabled = NO;
    self.webView = webView;
    [self.view addSubview:self.webView];
    self.webView.sd_layout
    .leftEqualToView(self.view)
    .topEqualToView(self.view)
    .rightEqualToView(self.view)
    .bottomEqualToView(self.view);
    
    _urlStr = [NSString stringWithFormat:@"%@details?device=1&name=%@&cantarget=1",LSMHostURL,self.articleId];
    
    [self.webView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:_urlStr]]];
    
//    UILabel *endLable = [[UILabel alloc] init];
//    endLable.textAlignment = NSTextAlignmentCenter;
//    endLable.text = @"（完）";
//    endLable.font = LSFontSize(14,LSScreenWidth);
//    endLable.textColor = LSTitleGrayColor3;
//    [self.scrollView addSubview:endLable];
//    endLable.sd_layout.centerXEqualToView(self.webView).topSpaceToView(self.webView, LSAutoVlaue(10, LSScreenHeight)).widthIs(LSAutoVlaue(100, LSScreenWidth)).heightIs(LSAutoVlaue(30, LSScreenHeight));
    
}

- (void)getData{
    MBProgressHUD *hud=[MBProgressHUD showHUDAddedTo:[UIApplication sharedApplication].keyWindow animated:YES];
    hud.mode=MBProgressHUDModeIndeterminate;
    
    
    
    [LSHttpEnclosureTool GET:LSArticleDetail parameters:@{@"articleId":self.articleId} resBlock:^(id responseObject) {
        if (responseObject) {
            MyLog(@"ArticleDetail --- %@",responseObject);
//            _articleList = [LSHomeArticleQueryList mj_objectWithKeyValues:responseObject];
            _titleStr = responseObject[@"ArticleTitle"];
            _describStr = responseObject[@"Description"];
            _imageUrl = responseObject[@"ListImgUrl"];
            [self initUI];
            [hud hideAnimated:YES];
        }
    }];
    
}


#pragma mark 🔥 shareMethod
- (void)action_ShareBtn:(UIButton *)sender{
    DXShareView *shareView = [[DXShareView alloc] init];
    [shareView showShareView];
    
    shareView.ChooseShareTypeBlock = ^(NSInteger type) {
        
        
        switch (type) {
            case DXShareTypeWechatSession://微信好友
            {
                MyLog(@"分享给微信好友");
                [self shareToWeChat:0];
            }
                break;
            case DXShareTypeWechatTimeline://微信朋友圈
            {
                MyLog(@"分享到微信朋友圈");
                [self shareToWeChat:1];
            }
                break;
            case DXShareTypeQQ://QQ好友
            {
                MyLog(@"分享给QQ好友");
                [self shareToQQFriend];
            }
                break;
            case DXShareTypeQzone://QQ空间
            {
                MyLog(@"分享到QQ空间");
                [self shareToQzone];
            }
                break;
                //        case DXShareTypeUrl://复制链接
                //        {
                //            UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
                //            pasteboard.string = self.shareConentType == DXShareContentTypeLink ? self.shareModel.url : self.shareModel.title;
                //            [XHToast showBottomWithText:@"复制成功"];
                //        }
                //            break;
            default:
                break;
        }
    };
}
- (void)shareToQQFriend{
    tencentOAuth = [[TencentOAuth alloc] initWithAppId:@"101489380"
                                           andDelegate:self];
//    MyLog(@"article --- %@",_articleList);
    
    
    
    QQApiNewsObject* img = [QQApiNewsObject objectWithURL:[NSURL URLWithString:_urlStr] title:_titleStr description:_describStr previewImageURL:[NSURL URLWithString:_imageUrl]];
    
    [img setCflag:kQQAPICtrlFlagQQShare];
    //请求帮助类,分享的所有基础对象，都要封装成这种请求对象。
    SendMessageToQQReq* req = [SendMessageToQQReq reqWithContent:img];
    QQApiSendResultCode sent = [QQApiInterface sendReq:req];
//
//    //通过自定义的qqdelegate来通知本controller，是否成功分享
//    appdelegate.delegate = self;
//
//    MyLog(@"QQApiSendResultCode %d",sent);
    
    [self handleSendResult:sent];
}
- (void)shareToQzone{
    tencentOAuth = [[TencentOAuth alloc] initWithAppId:@"101489380"
                                           andDelegate:self];
    
    QQApiNewsObject* img = [QQApiNewsObject objectWithURL:[NSURL URLWithString:_urlStr] title:_titleStr description:_describStr previewImageURL:[NSURL URLWithString:_imageUrl]];
    
    //请求帮助类,分享的所有基础对象，都要封装成这种请求对象。
    SendMessageToQQReq* req = [SendMessageToQQReq reqWithContent:img];
    QQApiSendResultCode sent = [QQApiInterface SendReqToQZone:req];
    
    //通过自定义的qqdelegate来通知本controller，是否成功分享
    appdelegate.delegate = self;
    
    MyLog(@"QQApiSendResultCode %d",sent);
    
    [self handleSendResult:sent];
}
- (void)shareToWeChat:(int )type{
  
    //创建分享内容对象
    WXMediaMessage *urlMessage = [WXMediaMessage message];
    urlMessage.title = _titleStr;//分享标题
    urlMessage.description = _describStr;//分享描述
    //    [urlMessage setThumbImage: [self zipImageWithUrl:_imageUrl]];
    
    UIImage * image = [UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:_imageUrl]]];
    NSData * data = [NSData dataWithContentsOfURL:[NSURL URLWithString:_imageUrl]];
    NSInteger i = data.length / 1024;
    NSData * imageData;
    if (i > 200) {
        imageData = UIImageJPEGRepresentation(image, 0.2);
        
    }else{
        
        imageData = UIImageJPEGRepresentation(image, 0.5);
    }
    UIImage * thumImage = [UIImage imageWithData:imageData];
    thumImage = [self scaleFromImage:thumImage toSize:CGSizeMake(200, 200)];
    //    thumImage = [self zipImageWithUrl:<#(id)#>]
    [urlMessage setThumbImage:thumImage];
    //创建多媒体对象
    WXWebpageObject *webObj = [WXWebpageObject object];
    webObj.webpageUrl = _urlStr;//分享链接
    urlMessage.mediaObject = webObj;
    
    SendMessageToWXReq *req = [[SendMessageToWXReq alloc] init];
    req.bText = NO;
    req.message = urlMessage;
    if (type == 0) {
        req.scene = WXSceneSession;
    }else{
        req.scene = WXSceneTimeline;
    }
    [WXApi sendReq:req];
    
    
}
#pragma mark --缩小图片
- (UIImage *) scaleFromImage: (UIImage *) image toSize: (CGSize) size{
    UIGraphicsBeginImageContext(size);
    [image drawInRect:CGRectMake(0, 0, size.width, size.height)];
    UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return newImage;
}


- (void)handleSendResult:(QQApiSendResultCode)sendResult{
    switch (sendResult)
    {
        case EQQAPIAPPNOTREGISTED:
        {
            UIAlertView *msgbox = [[UIAlertView alloc] initWithTitle:@"Error" message:@"App未注册" delegate:nil cancelButtonTitle:@"取消" otherButtonTitles:nil];
            [msgbox show];
            
            
            break;
        }
        case EQQAPIMESSAGECONTENTINVALID:
        case EQQAPIMESSAGECONTENTNULL:
        case EQQAPIMESSAGETYPEINVALID:
        {
            UIAlertView *msgbox = [[UIAlertView alloc] initWithTitle:@"Error" message:@"发送参数错误" delegate:nil cancelButtonTitle:@"取消" otherButtonTitles:nil];
            [msgbox show];
            
            
            break;
        }
        case EQQAPIQQNOTINSTALLED:
        {
            UIAlertView *msgbox = [[UIAlertView alloc] initWithTitle:@"Error" message:@"未安装手Q" delegate:nil cancelButtonTitle:@"取消" otherButtonTitles:nil];
            [msgbox show];
            
            
            break;
        }
        case EQQAPIQQNOTSUPPORTAPI:
        {
            UIAlertView *msgbox = [[UIAlertView alloc] initWithTitle:@"Error" message:@"API接口不支持" delegate:nil cancelButtonTitle:@"取消" otherButtonTitles:nil];
            [msgbox show];
            
            
            break;
        }
        case EQQAPISENDFAILD:
        {
            UIAlertView *msgbox = [[UIAlertView alloc] initWithTitle:@"Error" message:@"发送失败" delegate:nil cancelButtonTitle:@"取消" otherButtonTitles:nil];
            [msgbox show];
            
            
            break;
        }
        case EQQAPIVERSIONNEEDUPDATE:
        {
            UIAlertView *msgbox = [[UIAlertView alloc] initWithTitle:@"Error" message:@"当前QQ版本太低，需要更新" delegate:nil cancelButtonTitle:@"取消" otherButtonTitles:nil];
            [msgbox show];
            break;
        }
        default:
        {
            break;
        }
    }
}
#pragma mark QQ分享回调代理
/* 返回码 对照说明
 0   成功
 -1  参数错误
 -2  该群不在自己的群列表里面
 -3  上传图片失败
 -4  用户放弃当前操作
 -5  客户端内部处理错误
 */
-(void)shareSuccssWithQQCode:(NSInteger)code{
    MyLog(@"code %ld",(long)code);
    if (code == 0) {
        UIAlertView *aler = [[UIAlertView alloc]initWithTitle:@"警告" message:@"分享成功" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil];
        [aler show];
    }else{
        UIAlertView *aler = [[UIAlertView alloc]initWithTitle:@"警告" message:@"分享失败" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil];
        [aler show];
    }
}


#pragma mark - WKNavigationDelegate
//// 页面开始加载时调用
- (void)webView:(WKWebView *)webView didStartProvisionalNavigation:(WKNavigation *)navigation{
//    //修改字体大小 300%
//    [ webView evaluateJavaScript:@"document.getElementsByTagName('body')[0].style.webkitTextSizeAdjust= '400%'" completionHandler:nil];
//
//    //修改字体颜色  #9098b8
//    [ webView evaluateJavaScript:@"document.getElementsByTagName('body')[0].style.webkitTextFillColor= '#222222'" completionHandler:nil];
}
// 当内容开始返回时调用
- (void)webView:(WKWebView *)webView didCommitNavigation:(WKNavigation *)navigation{
    
}

// 页面加载完成之后调用
- (void)webView:(WKWebView *)webView didFinishNavigation:(WKNavigation *)navigation{
    [MBProgressHUD hideHUDForView:self.view];
    
//    self.webView.height=[webView.scrollView contentSize].height;
//    MyLog(@"webHeight --- %f",self.webView.height);
//    self.scrollView.contentSize = CGSizeMake(LSScreenWidth, self.webView.height);
    
//    CGSize actualSize = [webView sizeThatFits:CGSizeZero];
//    self.webView.height = actualSize.height;
//    MyLog(@"webHeight --- %f",self.webView.height);
//    self.scrollView.contentSize = CGSizeMake(LSScreenWidth, self.webView.height);
    CGFloat height = 0.0;
    [webView sizeToFit];
    height = webView.scrollView.contentSize.height;
    CGRect webFrame = webView.frame;
    webFrame.size.height = height;
    self.scrollView.height = height;
    webView.frame = webFrame;
   
    
//    [webView evaluateJavaScript:@"Math.max(document.body.scrollHeight, document.body.offsetHeight, document.documentElement.clientHeight, document.documentElement.scrollHeight, document.documentElement.offsetHeight)" completionHandler:^(id _Nullable result, NSError * _Nullable error) {
//        //获取页面高度，并重置webview的frame
//        CGFloat documentHeight = [result doubleValue];
//        self.webView.height = documentHeight/*显示不全*/;
//        MyLog(@"webHeight --- %f",documentHeight);
//        self.scrollView.contentSize = CGSizeMake(LSScreenWidth, self.webView.height + 170);
//    }];
}
// 页面加载失败时调用
- (void)webView:(WKWebView *)webView didFailProvisionalNavigation:(WKNavigation *)navigation{

}
// 接收到服务器跳转请求之后调用
- (void)webView:(WKWebView *)webView didReceiveServerRedirectForProvisionalNavigation:(WKNavigation *)navigation{

}
// 在收到响应后，决定是否跳转
- (void)webView:(WKWebView *)webView decidePolicyForNavigationResponse:(WKNavigationResponse *)navigationResponse decisionHandler:(void (^)(WKNavigationResponsePolicy))decisionHandler{

    MyLog(@"%@",navigationResponse.response.URL.absoluteString);
    //允许跳转
    decisionHandler(WKNavigationResponsePolicyAllow);
    //不允许跳转
    //decisionHandler(WKNavigationResponsePolicyCancel);
}
// 在发送请求之前，决定是否跳转
- (void)webView:(WKWebView *)webView decidePolicyForNavigationAction:(WKNavigationAction *)navigationAction decisionHandler:(void (^)(WKNavigationActionPolicy))decisionHandler{

    MyLog(@"%@",navigationAction.request.URL.absoluteString);
    //允许跳转
    decisionHandler(WKNavigationActionPolicyAllow);
    //不允许跳转
    //decisionHandler(WKNavigationActionPolicyCancel);
}
#pragma mark - WKUIDelegate
// 创建一个新的WebView
- (WKWebView *)webView:(WKWebView *)webView createWebViewWithConfiguration:(WKWebViewConfiguration *)configuration forNavigationAction:(WKNavigationAction *)navigationAction windowFeatures:(WKWindowFeatures *)windowFeatures{
    return [[WKWebView alloc]init];
}
// 输入框
- (void)webView:(WKWebView *)webView runJavaScriptTextInputPanelWithPrompt:(NSString *)prompt defaultText:(nullable NSString *)defaultText initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void (^)(NSString * __nullable result))completionHandler{
    completionHandler(@"http");
}
// 确认框
- (void)webView:(WKWebView *)webView runJavaScriptConfirmPanelWithMessage:(NSString *)message initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void (^)(BOOL result))completionHandler{
    completionHandler(YES);
}
// 警告框
- (void)webView:(WKWebView *)webView runJavaScriptAlertPanelWithMessage:(NSString *)message initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void (^)(void))completionHandler{
    MyLog(@"%@",message);
    completionHandler();
}

- (void)dealloc{
    
    
    MyLog(@"%@ dealloc",NSStringFromClass([self class]));
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
